<template>
	<n-card>
		<n-space vertical>
			<!-- 头部操作区 -->
			<n-space>
				<!-- 修改后 -->
				<n-select
					v-model="currentType"
					placeholder="请选择素材类型"
					style="width: 120px"
					@update:value="handleTypeChange"
					:options="materialTypeOptions"
				/>
				<n-input
					v-model="searchKeyword"
					placeholder="请输入素材名称或ID"
					style="width: 300px"
					clearable
					@keypress.enter="handleSearch"
				/>
				<n-button type="primary" @click="handleSearch"> 搜索 </n-button>
				<n-button type="primary" @click="handleUpload"> 上传素材 </n-button>
				<n-button type="warning" @click="handleSync"> 同步素材 </n-button>
				<n-button type="error" @click="handleBatchDelete"> 批量删除 </n-button>
			</n-space>

			<!-- 素材统计 -->
			<n-card>
				<n-row>
					<n-col :span="4">
						<n-statistic label="活跃用户">
							{{ materialCount.total }}
						</n-statistic>
					</n-col>
					<n-col :span="4">
						<n-statistic label="图片素材">
							{{ materialCount.image }}
						</n-statistic>
					</n-col>
					<n-col :span="4">
						<n-statistic label="语音素材">
							{{ materialCount.voice }}
						</n-statistic>
					</n-col>
					<n-col :span="4">
						<n-statistic label="视频素材">
							{{ materialCount.video }}
						</n-statistic>
					</n-col>
					<n-col :span="4">
						<n-statistic label="图文素材">
							{{ materialCount.news }}
						</n-statistic>
					</n-col>
				</n-row>
			</n-card>

			<!-- 素材列表 -->
			<n-data-table
				:checked-row-keys="selectedMaterialIds"
				:columns="columns"
				:data="materialList"
				:loading="loading"
				:row-key="(row) => row.mediaId"
				:pagination="pagination"
				@update:checked-row-keys="updateSelectedMaterial"
				@update:page="handleCurrentChange"
				@update:page-size="handleSizeChange"
			>
			</n-data-table>
		</n-space>
	</n-card>
	<!-- 上传对话框 -->
	<n-modal v-model:show="uploadDialogVisible">
		<n-card
			:title="'上传素材'"
			style="width: 600px; height: 100%; position: fixed; right: 0px; top: 0px"
			:bordered="false"
			role="dialog"
			aria-modal="true"
		>
			<n-form>
				<n-form-item label="素材类型" required>
					<n-select
						v-model:value="uploadForm.type"
						placeholder="请选择素材类型"
						:options="materialTypeOptions"
					>
					</n-select>
				</n-form-item>
				<n-form-item label="素材文件" required>
					<n-upload
						:default-upload="false"
						@change="handleFileChange"
						:show-file-list="true"
						class="custom-upload-area"
					>
						<div class="upload-content">
							<div class="upload-icon">
								<n-icon size="40">
									<CloudUploadOutline />
								</n-icon>
							</div>
							<div class="upload-text">
								<div>点击或拖拽文件到此处上传</div>
								<div class="upload-hint">支持单个文件上传</div>
							</div>
						</div>
					</n-upload>
				</n-form-item>
				<n-form-item v-if="uploadForm.type === 'video'" label="标题">
					<n-input
						v-model:value="uploadForm.title"
						placeholder="请输入视频标题"
					/>
				</n-form-item>
				<n-form-item v-if="uploadForm.type === 'video'" label="描述">
					<n-input
						v-model:value="uploadForm.description"
						type="textarea"
						placeholder="请输入视频描述"
					/>
				</n-form-item>
			</n-form>
			<template #footer>
				<n-space>
					<n-button @click="uploadDialogVisible = false">取消</n-button>
					<n-button type="primary" @click="handleConfirmUpload">确定</n-button>
				</n-space>
			</template>
		</n-card>
	</n-modal>

	<!-- 详情对话框 -->
	<n-modal v-model:show="detailDialogVisible">
		<n-card
			:title="'素材详情'"
			style="width: 800px; height: 100%; position: fixed; right: 0px; top: 0px"
			:bordered="false"
			role="dialog"
			aria-modal="true"
		>
			<n-scrollbar>
				<n-descriptions column="1">
					<n-descriptions-item label="素材ID">{{
						currentMaterial?.mediaId
					}}</n-descriptions-item>
					<n-descriptions-item label="素材名称">{{
						currentMaterial?.name
					}}</n-descriptions-item>
					<n-descriptions-item label="素材类型">{{
						getTypeText(currentMaterial?.type || "")
					}}</n-descriptions-item>
					<n-descriptions-item label="创建时间">{{
						currentMaterial?.createTime
					}}</n-descriptions-item>
					<n-descriptions-item label="素材链接">{{
						currentMaterial?.url
					}}</n-descriptions-item>
				</n-descriptions>

				<!-- 图片预览 -->
				<n-space
					justify="center"
					v-if="
						currentMaterial?.type === 'image' ||
						currentMaterial?.type === 'thumb'
					"
				>
					<n-image width="100" :src="currentMaterial?.url" />
				</n-space>

				<!-- 图文素材详情 -->
				<n-list bordered v-if="materialNewsInfo">
					<n-list-item
						v-for="(news, index) in materialNewsInfo?.newsItem"
						:key="index"
					>
						<template #prefix>
							<n-avatar v-if="news.thumbUrl" :src="news.thumbUrl" />
						</template>
						<n-thing :title="news.title" :description="news.digest">
							<template #footer>
								<n-space vertical>
									<n-text>作者：{{ news.author }}</n-text>
									<div v-html="news.content"></div>
									<n-text>
										<a :href="news.contentSourceUrl" target="_blank"
											>原文链接</a
										>
									</n-text>
								</n-space>
							</template>
						</n-thing>
					</n-list-item>
				</n-list>

				<!-- 视频素材详情 -->
				<n-list bordered v-if="materialVideoInfo">
					<n-list-item>
						<n-thing
							:title="materialVideoInfo.title"
							:description="materialVideoInfo.description"
						>
							<template #action>
								<a :href="materialVideoInfo.downUrl" target="_blank"
									>下载视频</a
								>
							</template>
						</n-thing>
					</n-list-item>
				</n-list>
			</n-scrollbar>
		</n-card>
	</n-modal>
</template>

<script setup>
	import { ref, reactive, onMounted } from "vue";
	import { wechatMaterialApi } from "@server/api/wechatMaterialApi";
	import { useMessage, useDialog } from "naive-ui";
	import { CloudUploadOutline, Warning } from "@vicons/ionicons5";
	import { NTag, NButton, NPopconfirm, NSpace, NText, NIcon } from "naive-ui";

	const message = useMessage();
	const dialog = useDialog(); // 添加 dialog 实例

	// 状态管理
	const loading = ref(false);
	const materialList = ref([]);
	const total = ref(0);
	const currentPage = ref(1);
	const pageSize = ref(10);
	const currentType = ref("image");
	const searchKeyword = ref("");
	const selectedMaterialIds = ref([]);
	const materialCount = ref({
		total: 0,
		image: 0,
		voice: 0,
		video: 0,
		news: 0,
	});
	const materialTypeOptions = ref([
		{ label: "图片", value: "image" },
		{ label: "语音", value: "voice" },
		{ label: "视频", value: "video" },
	]);

	// 表格列配置
	const columns = [
		{
			type: "selection",
			width: 40,
		},
		{
			title: "素材ID",
			key: "mediaId",
			ellipsis: true,
		},
		{
			title: "素材名称",
			key: "name",
			ellipsis: true,
		},
		{
			title: "类型",
			key: "type",
			render: (row) =>
				h(
					NTag,
					{ type: getTypeTagType(row.type) },
					{
						default: () => getTypeText(row.type),
					}
				),
		},
		{
			title: "创建时间",
			key: "createTime",
		},
		{
			title: "预览",
			key: "preview",
			render: (row) =>
				h(
					NButton,
					{
						text: true,
						type: "primary",
						onClick: () => handleView(row),
					},
					{
						default: () => "预览",
					}
				),
			width: 80,
		},
		// 修改columns数组中的操作列定义
		{
			title: "操作",
			key: "action",
			render: (row) => {
				// 使用更明确的函数定义方式
				const handleConfirmDelete = () => {
					console.log("删除素材:", row.mediaId); // 添加日志以便调试
					handleDelete(row.mediaId);
				};

				return h(NSpace, null, [
					h(
						NPopconfirm,
						{
							positiveText: "确定",
							negativeText: "取消",
							onPositiveClick: handleConfirmDelete, // 使用onPositiveClick而不是positiveClick
						},
						{
							trigger: () =>
								h(
									NButton,
									{
										text: true,
										type: "error",
									},
									{ default: () => "删除" }
								),
							icon: () => h(NIcon, null, { default: () => h(Warning) }),
							default: () => "确定要删除该素材吗？",
						}
					),
				]);
			},
			width: 80,
		},
	];
	// 对话框状态
	const uploadDialogVisible = ref(false);
	const detailDialogVisible = ref(false);
	const currentMaterial = ref(null);
	const materialNewsInfo = ref(null);
	const materialVideoInfo = ref(null);

	// 上传表单相关
	const uploadForm = reactive({
		type: "image",
		title: "",
		description: "",
	});
	const fileList = ref([]);
	const selectedFile = ref(null);

	// 辅助函数：获取类型标签样式
	const getTypeTagType = (type) => {
		const typeMap = {
			image: "primary",
			voice: "success",
			video: "warning",
			thumb: "info",
			news: "danger",
		};
		return typeMap[type] || "default";
	};

	// 辅助函数：获取类型文本
	const getTypeText = (type) => {
		const typeMap = {
			image: "图片",
			voice: "语音",
			video: "视频",
			thumb: "缩略图",
			news: "图文",
		};
		return typeMap[type] || type;
	};

	// 处理查看
	const handleView = async (material) => {
		currentMaterial.value = material;
		materialNewsInfo.value = null;
		materialVideoInfo.value = null;

		try {
			// 如果是图文素材，获取详情
			if (material.type === "news") {
				materialNewsInfo.value = await wechatMaterialApi.getMaterialNewsInfo(
					material.mediaId
				);
			}
			// 如果是视频素材，获取详情
			else if (material.type === "video") {
				materialVideoInfo.value = await wechatMaterialApi.getMaterialVideoInfo(
					material.mediaId
				);
			}

			detailDialogVisible.value = true;
		} catch (error) {
			message.error("获取素材详情失败");
			console.error("获取素材详情失败:", error);
		}
	};

	// 处理删除
	const handleDelete = async (mediaId) => {
		try {
			await wechatMaterialApi.deleteMaterial(mediaId);
			message.success("删除成功");
			loadMaterialList();
		} catch (error) {
			message.error("删除失败");
			console.error("删除素材失败:", error);
		}
	};

	// 初始化数据
	onMounted(() => {
		loadMaterialCount();
		loadMaterialList();
	});

	// 加载素材总数
	const loadMaterialCount = async () => {
		try {
			const result = await wechatMaterialApi.getMaterialCount();
			materialCount.value = result;
		} catch (error) {
			message.error("获取素材总数失败");
			console.error("获取素材总数失败:", error);
		}
	};

	// 加载素材列表
	const loadMaterialList = async () => {
		loading.value = true;
		try {
			let materials = [];
			const offset = (currentPage.value - 1) * pageSize.value;

			if (currentType.value === "news") {
				// 先获取本地素材列表
				materials = await wechatMaterialApi.getLocalMaterialList();

				// 根据类型和关键词过滤
				materials = materials.filter((item) => item.type === currentType.value);
				if (searchKeyword.value) {
					const keyword = searchKeyword.value.toLowerCase();
					materials = materials.filter(
						(item) =>
							item.name?.toLowerCase().includes(keyword) ||
							item.mediaId?.toLowerCase().includes(keyword)
					);
				}

				// 分页
				total.value = materials.length;
				materials = materials.slice(offset, offset + pageSize.value);
			} else {
				// 获取特定类型的素材列表
				const result = await wechatMaterialApi.getMaterialFileBatch(
					currentType.value,
					searchKeyword.value,
					offset,
					pageSize.value
				);
				materials = result.records;
				total.value = result.total;
			}

			materialList.value = materials;
		} catch (error) {
			message.error("获取素材列表失败");
			console.error("获取素材列表失败:", error);
		} finally {
			loading.value = false;
		}
	};

	// 处理类型切换
	const handleTypeChange = () => {
		currentPage.value = 1;
		loadMaterialList();
	};

	// 处理搜索
	const handleSearch = () => {
		currentPage.value = 1;
		loadMaterialList();
	};

	// 处理刷新
	const handleRefresh = () => {
		loadMaterialCount();
		loadMaterialList();
	};

	// 处理同步
	const handleSync = async () => {
		try {
			dialog.success({
				title: "确认同步",
				content: "确定要同步微信素材吗？这将会清空本地素材数据并重新同步",
				positiveText: "确定",
				negativeText: "取消",
				draggable: true,
				onPositiveClick: () => {
					loading.value = true;
					wechatMaterialApi.syncMaterials();
					loadMaterialList();
					message.success("同步完成");
				},
				onNegativeClick: () => {
					message.warning("取消同步");
				},
			});
		} catch (error) {
			message.error("同步素材失败");
			console.error("同步素材失败:", error);
		} finally {
			loading.value = false;
		}
	};

	// 处理分页变化
	const handleSizeChange = (size) => {
		pageSize.value = size;
		currentPage.value = 1;
		loadMaterialList();
	};

	const handleCurrentChange = (current) => {
		currentPage.value = current;
		loadMaterialList();
	};

	// 处理批量删除
	const handleBatchDelete = async () => {
		if (selectedMaterialIds.value.length === 0) {
			message.warning("请选择要删除的素材");
			return;
		}

		try {
			dialog.success({
				title: "确认",
				content: `确定要删除选中的${selectedMaterialIds.value.length}个素材吗？`,
				positiveText: "确定",
				negativeText: "取消",
				draggable: true,
				onPositiveClick: async () => {
					loading.value = true;
					await wechatMaterialApi.batchDeleteMaterials(selectedMaterialIds.value);
					selectedMaterialIds.value = [];
					loadMaterialList();
					message.success("删除成功");
				},
				onNegativeClick: () => {
					message.warning("取消删除");
				},
			});
		} catch (error) {
			if (error !== "cancel") {
				message.error("批量删除失败");
				console.error("批量删除素材失败:", error);
			}
		} finally {
			loading.value = false;
		}
	};

	// 处理上传
	const handleUpload = () => {
		// 重置表单
		Object.assign(uploadForm, {
			type: "image",
			title: "",
			description: "",
		});
		fileList.value = [];
		selectedFile.value = null;

		// 显示对话框
		uploadDialogVisible.value = true;
	};

	// 处理文件变化
	const handleFileChange = (options) => {
		// 检查options是否为数组（旧版本可能直接传fileList）
		const fileList = Array.isArray(options) ? options : options?.fileList || [];

		if (fileList && fileList.length > 0) {
			// Naive UI的n-upload组件返回的fileList格式可能有所不同
			// 检查fileList中的项是否直接包含file属性，或者本身就是File对象
			const lastFile = fileList[fileList.length - 1];
			selectedFile.value = lastFile.file || lastFile;

			// 同时更新fileList状态，以便显示已选择的文件
			fileList.value = fileList;
		}
	};

	// 处理确认上传
	const handleConfirmUpload = async () => {
		if (!selectedFile.value) {
			message.warning("请选择文件");
			return;
		}

		try {
			loading.value = true;
			await wechatMaterialApi.uploadMaterial(
				uploadForm.type,
				selectedFile.value,
				uploadForm.title,
				uploadForm.description
			);
			message.success("上传成功");
			uploadDialogVisible.value = false;
			// loadMaterialCount();
			loadMaterialList();
		} catch (error) {
			message.error("上传失败");
			console.error("上传素材失败:", error);
		} finally {
			loading.value = false;
		}
	};

	// 处理关闭详情
	const handleCloseDetail = () => {
		currentMaterial.value = null;
		materialNewsInfo.value = null;
		materialVideoInfo.value = null;
	};

	const updateSelectedMaterial = (keys) => {
		selectedMaterialIds.value = keys;
	};
</script>
<style scoped>
	.custom-upload-area {
		width: 100%;
	}

	.upload-content {
		border: 2px dashed #d9d9d9;
		border-radius: 8px;
		padding: 40px 20px;
		text-align: center;
		transition: all 0.3s;
		background-color: #fafafa;
	}

	.upload-content:hover {
		border-color: #1890ff;
		background-color: #e6f7ff;
	}

	.upload-icon {
		font-size: 48px;
		color: #999;
		margin-bottom: 16px;
	}

	.upload-text {
		color: #666;
	}

	.upload-hint {
		font-size: 12px;
		color: #999;
		margin-top: 8px;
	}
</style>